package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao checkGroupDao;

    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.add ( checkGroup );
        setCheckGroupAndCheckItem ( checkGroup, checkitemIds );

    }


    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage ();
        Integer pageSize = queryPageBean.getPageSize ();
        String queryString = queryPageBean.getQueryString ();
        PageHelper.startPage ( currentPage, pageSize );
        Page<CheckGroup> page = checkGroupDao.findPage ( queryString );
        List<CheckGroup> rows = page.getResult ();
        long total = page.getTotal ();
        return new PageResult ( total, rows );
    }

    @Override
    public void delete(Integer id) {
        Long count = checkGroupDao.findById ( id );
        if (count > 0) {
            throw new RuntimeException ( "此检查组被引用，不能删除" );
        } else {
            checkGroupDao.deletesetCheckGroupAndCheckItem ( id );
            checkGroupDao.delete ( id );
        }
    }

    @Override
    public CheckGroup findGroupById(Integer id) {
        return checkGroupDao.findGroupById ( id );
    }

    @Override
    public Integer[] findItemsByGroupId(Integer id) {
        Integer[] items = checkGroupDao.findItemsByGroupId ( id );
        return items;
    }

    @Override
    public void update(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.update ( checkGroup );
        checkGroupDao.deletesetCheckGroupAndCheckItem ( checkGroup.getId () );
        setCheckGroupAndCheckItem ( checkGroup, checkitemIds );
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll ();
    }

    public void setCheckGroupAndCheckItem(CheckGroup checkGroup, Integer[] checkitemIds) {
        if (checkitemIds != null && checkitemIds.length > 0) {
            for (Integer checkitemId : checkitemIds) {
                Map<String, Integer> idMap = new HashMap<> ();
                idMap.put ( "checkgroup_id", checkGroup.getId () );
                idMap.put ( "checkitem_id", checkitemId );
                checkGroupDao.setCheckGroupAndCheckItem ( idMap );
            }
        }

    }

}





